# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        # 递归法，前序遍历
        # if root is None:
        #     return root
        # root.left,root.right = root.right,root.left # swap
        # self.invertTree(root.left)
        # self.invertTree(root.right)
        # return root
        # 迭代法
        if not root:
            return None
        stack=[root]
        while stack:
            Node = stack.pop()
            Node.left,Node.right = Node.right,Node.left
            if Node.left:
                stack.append(Node.left)
            if Node.right:
                stack.append(Node.right)
        return root
